﻿using AutoMapper;
using B.S.Filtration.ErrorCode;
using B.S.Filtration.Infratrveture;
using B.S.Filtration.Read.Api.Application.Command.DOMDetails1;
using B.S.Filtration.Read.Api.Dto;
using Dapper;
using MediatR;
using System.Data;

namespace B.S.Filtration.Read.Api.Application.CommandHander.DOMDetails1
{
    public class GetDOMDetails1Hander : IRequestHandler<GetDOMDetails1Command, APIResult<List<DOMDetails1Dto>>>
    {
        private readonly IMapper mapper;
        private readonly DapperContext db;

        public GetDOMDetails1Hander(IMapper mapper, DapperContext db)
        {
            this.mapper = mapper;
            this.db = db;
        }

        /// <summary>
        /// 根据DOMId查询DOM配件详情，若DOMId为空则查询所有记录
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<List<DOMDetails1Dto>>> Handle(GetDOMDetails1Command request, CancellationToken cancellationToken)
        {
            APIResult<List<DOMDetails1Dto>> result = new APIResult<List<DOMDetails1Dto>>();
            var parameters = new DynamicParameters();

            // 根据DOMId是否有值动态构建SQL查询
            var query = request.DOMId.HasValue
                ? "SELECT * FROM DOMDetails WHERE DOMId = @DOMId"
                : "SELECT * FROM DOMDetails";

            if (request.DOMId.HasValue)
            {
                parameters.Add("DOMId", request.DOMId, DbType.Int32);
            }

            try
            {
                // 执行查询
                var data = await db.QueryAsync<DOMDetails1Dto>(query, parameters);

                result.data = data.ToList();
                result.code = APIResultCode.success;
                result.msg = request.DOMId.HasValue
                    ? "按ID查询成功"
                    : "查询所有记录成功";
            }
            catch (Exception ex)
            {
                // 错误处理
                result.code = APIResultCode.failed;
                result.msg = "查询失败: " + ex.Message;
                result.data = new List<DOMDetails1Dto>();
            }

            return result;
        }
    }
}